﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Runtime.InteropServices;

using System.Data;
using System.Configuration;
using System.Collections;


using System.Xml;
using System.Text;



using System.Xml;
using System.Text;

using Cisoft.Booking.Model;
using Cisoft.Booking.BLL;

public partial class AutoScan_AutoInbox : System.Web.UI.Page
{
    private static RuleBO ruleBO = new RuleBO();
    private static RuleMO ruleMO = new RuleMO();


    [DllImport("EUCPComm.dll", EntryPoint = "ReceiveSMS")]
    public static extern int ReceiveSMS(string sn, deleSQF mySmsContent);
    public delegate void deleSQF(string mobile, string senderaddi, string recvaddi, string ct, string sd, ref int flag);
    deleSQF mySmsContent = new deleSQF(getSMSContent);

    //短信上行实体类
    public static Cisoft.Cisoft3G.Model.InboxMO model = new Cisoft.Cisoft3G.Model.InboxMO();
    //短信上行业务逻辑类
    public static Cisoft.Cisoft3G.BLL.InboxBO bll = new Cisoft.Cisoft3G.BLL.InboxBO();
    //亿美产品序列号
    public static string EmeyKey = System.Configuration.ConfigurationSettings.AppSettings["EmeyKey"].ToString();
    //亿美产品密码
    public static string EmeyPwd = System.Configuration.ConfigurationSettings.AppSettings["EmeyPassword"].ToString();

    public static string ss = string.Empty;

    protected void Page_Load(object sender, EventArgs e)
    {
        LinkButton1_Click1(sender, e);
    }

    /// <summary>
    /// 启动服务
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        //lblTbPre.Text = "服务运行中...";
        //txt_Time.Enabled = false;
        //lb_EndService.Enabled = true;
        //lb_StartService.Enabled = false;

        
    }
    /// <summary>
    /// 听停止服务
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void lb_EndService_Click(object sender, EventArgs e)
    {
        //lblTbPre.Text = "请输入服务间隔：";
        //txt_Time.Enabled = true;
        //lb_EndService.Enabled = false;
        //lb_StartService.Enabled = true;
    }

    /// <summary>
    /// 接收短信内容
    /// </summary>
    /// <param name="mobile">上行手机号码</param>
    /// <param name="senderaddi">发送者附加号码</param>
    /// <param name="recvaddi">接受者附加号码</param>
    /// <param name="ct">上行短信内容</param>
    /// <param name="sd">接收时间</param>
    /// <param name="flag">是否有短信 1表示有短信，0表示没有短信</param>
    public static void getSMSContent(string mobile, string senderaddi, string recvaddi, string ct, string sd, ref int flag)
    {
        string mob = mobile;
        string content = ct;
        int myflag = flag;
        if (flag > 0)
        {
            //是否已经存在false为不存在，true为存在
            bool isExsist = false;
            List<Cisoft.Cisoft3G.Model.InboxMO> modelList = bll.GetModelList(" IB_SendTime >= '" + DateTime.Now.AddMinutes(-10).ToString() + "' " );
            foreach (Cisoft.Cisoft3G.Model.InboxMO mo in modelList)
            {
                if (mo.IB_Send == mobile && mo.IB_SendTime == GetTime(sd) && mo.IB_SMContent == ct)
                {
                    isExsist = true;
                    break;
                }
            }
            if (isExsist == false)
            {
                model.IB_InboxID = bll.GetMaxId();
                model.IB_SmsID = System.Guid.NewGuid().ToString();
                model.IB_Send = mob;
                model.IB_SendTime = GetTime(sd);
                model.IB_SMContent = content;
                model.RT_Type_FK = 1;

                try
                {
                    bll.Add(model);
                }
                catch (Exception ex)
                {

                }
                //扩展逻辑 投票
                DoVote(model);
            }


           
        }

        ss += "上行号码：" + mob + "<br>短信内容：" + content + "<br>" + "时间：" + sd + "<br>是否有短信：" + (flag == 0 ? "没有" : "有") + "<p>-------</p>";
    }



    protected void LinkButton1_Click1(object sender, EventArgs e)
    {
        deleSQF mySmsContent = new deleSQF(getSMSContent);
        //接收短信                序列号       函数指针            
        int result = 2;
        while (result == 2)
        {
            //当result = 2 时，说明还有下一批短信等待接收，这时需重新再调用一次ReceiveSMS方法  {                
            result = ReceiveSMS(EmeyKey, mySmsContent);
            if (result == 1)
            {
                lblResult.Text += "接收短信成功'" + DateTime.Now.ToString() + "'<br/>";                  //ReceiveMsg recMsg = new ReceiveMsg();                
            }
            else if (result == 101)
            {
                lblResult.Text += "网络故障'" + DateTime.Now.ToString() + "<br>";
            }
            else if (result == 102)
            {
                lblResult.Text += "其它故障'" + DateTime.Now.ToString() + "<br>";
            }
            else if (result == 105)
            {
                lblResult.Text += "参数指针为空'" + DateTime.Now.ToString() + "<br>";
            }
            else if (result == 0)
            {
                lblResult.Text += "失败'" + DateTime.Now.ToString() + "<br>";
            }
            else if (result == -1)
            {
                lblResult.Text += "未知故障'" + DateTime.Now.ToString() + "<br>";
            }
        }

        Label1.Text = ss;
    }

    /// <summary>
    /// 将字符串转换为时间
    /// </summary>
    /// <param name="input"></param>
    public static DateTime GetTime(string input)
    { 
        return Convert.ToDateTime(input.Substring(0,4) + "-" + input.Substring(4,2) + "-" + 
                input.Substring(6,2) + " " + input.Substring(8,2) + ":" + input.Substring(10,2) + ":" + input.Substring(12,2));
    }


    #region 根据分隔符获取短信发送类型
    /// <summary>
    /// 根据分隔符获取短信发送类型
    /// </summary>
    /// <param name="dr">传入的数据行</param>
    private static string GetSMType(string messagecontent)
    {
        string str = "";
        //if (dr["messagecontent"].ToString() != "")
        //{
        //    ruleMO = ruleBO.GetModel(" RuleCode = '" + RuleCode + "'");

        //str = dr["messagecontent"].ToString();
        str = messagecontent;
        
        if (str.IndexOf("#") >= 0)
        {
            str = str.Split('#')[0].ToString();
        }
        //}
        return str;
    }
    #endregion

    #region 获取投票分隔符
    /// <summary>
    /// 获取投票分隔符
    /// </summary>
    /// <param name="Content">规则代码</param>
    /// <returns></returns>
    private static string GetBreakSymbol(string RuleCode)
    {
        ruleMO = ruleBO.GetModel(" RuleCode = '" + RuleCode + "'");
        string str = null;
        if (ruleMO != null)
        {
            str = ruleMO.RuleBreakSymbol;
        }
        return str;
    }
    #endregion

    #region 投票
    public static void DoVote(Cisoft.Cisoft3G.Model.InboxMO model)
    {
        

        #region 投票
        //投票
        if (GetSMType(model.IB_SMContent) == "TP")
        {

            Cisoft.Cisoft3G.BLL.InboxBO smBO = new Cisoft.Cisoft3G.BLL.InboxBO();
            Cisoft.Cisoft3G.Model.InboxMO smMO = new Cisoft.Cisoft3G.Model.InboxMO();


            //获取投票分隔符
            char breakSymbol = Convert.ToChar(GetBreakSymbol("TP"));
            //如果短信里的投票分隔符与规则表里的一致
            if (model.IB_SMContent.IndexOf(breakSymbol) > 0)
            {
                string[] strContents = null;
                int voteid = 0;
                int voteoptionnumber = 0;
                try
                {
                    //使用分隔符分隔短信内容
                    strContents = model.IB_SMContent.Split(breakSymbol);
                    //取出投票ID
                    voteid = int.Parse(strContents[1].ToString());
                    //取出投票选项
                    voteoptionnumber = int.Parse(strContents[2].ToString());
                }
                catch
                {

                }
                //判断是否存在该投票
                bool voteIsExsist = false;
                foreach (DataRow drforvote in new Cisoft.Booking.BLL.VoteBO().GetAllList().Tables[0].Rows)
                {
                    if (strContents[1].ToString() == drforvote["VoteID"].ToString())
                    {
                        voteIsExsist = true;
                        break;
                    }
                }
                if (voteIsExsist)
                {
                    //判断投票时间是否过期
                    VoteBO vBO = new VoteBO();
                    VoteMO vMO = new VoteMO();

                    vMO = vBO.GetModel(Convert.ToInt32(strContents[1].ToString()));
                    if (Convert.ToDateTime(model.IB_SendTime) >= Convert.ToDateTime(vMO.VoteStartTime) && Convert.ToDateTime(model.IB_SendTime) <= Convert.ToDateTime(vMO.VoteEndTime))
                    {
                        //判断是否已经投过票(遍历短信表，找到相同记录)
                        bool voteIsRepeate = false;
                        DataSet dsforsm = smBO.GetList(" RT_Type_FK =3 and IB_Send= '" + model.IB_Send + "'");
                        if (dsforsm.Tables[0].Rows.Count > 0)
                        {
                            foreach (DataRow drforsm in dsforsm.Tables[0].Rows)
                            {
                                if (drforsm["IB_SMContent"].ToString().IndexOf(strContents[0].ToString() + breakSymbol + strContents[1].ToString() + breakSymbol) >= 0)
                                {
                                    voteIsRepeate = true;
                                    break;
                                }
                            }
                        }
                        if (voteIsRepeate)
                        {
                            SendTimeSMS(model.IB_Send, "您已投过票，请不要重复投票！",DateTime.Now.AddMinutes(5));
                            
                        }
                        //判断是否存在该选项
                        bool voteOptionIsExsist = false;
                        foreach (DataRow drforvoteoption in new Cisoft.Booking.BLL.VoteOptionBO().GetAllList().Tables[0].Rows)
                        {
                            if (strContents[2].ToString() == drforvoteoption["VoteOptionNumber"].ToString() && strContents[1].ToString() == drforvoteoption["VoteID_FK"].ToString())
                            {
                                voteOptionIsExsist = true;
                                break;
                            }
                        }

                        if (voteOptionIsExsist)
                        {
                            //写入系统待发短信表
                            //object[] send = { strType, mobile, "系统", dr["messagecontent"].ToString() };
                            object[] send = { "3", model.IB_Send, model.IB_SMContent.ToString() };
                            if (InsertShortMessage(send) > 0)
                            {
                                //更新系统投票表(投票选项计数器)
                                VoteOptionMO voMO = new VoteOptionMO();
                                VoteOptionBO voBO = new VoteOptionBO();
                                voMO = voBO.GetModel(voteid, voteoptionnumber);
                                if (voMO != null)
                                {
                                    voMO.VoteCount += 1;
                                    voBO.Update(voMO);
                                    //回复投票成功短信
                                    //if (SendMessageWithRecord(mobile, "您好！您的投票信息已成功发送,谢谢您的参与!") > 0)
                                    //{
                                    //    //系统短信表
                                    //    InsertShortMessage(mobile, strReply);
                                    //}

                                    SendTimeSMS(model.IB_Send, "您好！您的投票信息已成功发送,谢谢您的参与！", DateTime.Now.AddMinutes(5));

                                    
                                }
                            }
                        }
                        else
                        {

                            SendTimeSMS(model.IB_Send, "不存在该投票选项！", DateTime.Now.AddMinutes(5));
                            
                        }
                    }
                    else
                    {
                        SendTimeSMS(model.IB_Send, "投票已结束,谢谢您的大力支持！", DateTime.Now.AddMinutes(5));
                        
                    }
                }
                //如果不存在,发送错误提示短信
                else
                {
                    SendTimeSMS(model.IB_Send, "投票代码为[" + strContents[1].ToString() + "]的投票不存在，请确认是否存在该投票", DateTime.Now.AddMinutes(5));
                    
                }
            }
            //break;
        }
        #endregion
    }
    #endregion


    #region 自定义方法定时发送短信
    private static void SendTimeSMS(string mobile, string strContent, DateTime time)
    {
        
        Cisoft.Cisoft3G.BLL.OutboxBO bll = new Cisoft.Cisoft3G.BLL.OutboxBO();
        Cisoft.Cisoft3G.Model.OutboxMO model = new Cisoft.Cisoft3G.Model.OutboxMO();
        try
        {
            
                model.OB_OutBoxiD = bll.GetMaxId();
                model.OB_Recive = mobile;
                model.OB_SendTime = time;
                model.OB_SMContent = strContent;
                model.OB_SmsID = System.Guid.NewGuid().ToString();
                model.RT_Type_FK = 3;

                bll.Add(model);
            
        }
        catch (Exception ex)
        {

        }
    }
    #endregion

    /// <summary>
    /// 写入系统短信表
    /// </summary>
    /// <param name="al">ArrayList</param>
    private static int InsertShortMessage(object[] al)
    {
        int result = 0;
        if (al != null)
        {
            Cisoft.Cisoft3G.BLL.OutboxBO bll = new Cisoft.Cisoft3G.BLL.OutboxBO();
            Cisoft.Cisoft3G.Model.OutboxMO model = new Cisoft.Cisoft3G.Model.OutboxMO();
            try
            {

                model.OB_OutBoxiD = bll.GetMaxId();
                model.OB_Recive = al[1].ToString();
                model.OB_SendTime = DateTime.Now;
                model.OB_SMContent = al[2].ToString();
                model.OB_SmsID = System.Guid.NewGuid().ToString();
                model.RT_Type_FK = int.Parse(al[0].ToString());

                bll.Add(model);
                result = 1;

            }
            catch (Exception ex)
            {

            }
        }
        return result;
    }
}
